﻿using Liu_Project.Entity.Admin;
using System;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Liu_Project.Utils
{
    public static class LogDBHelper
    {
        public static async Task LogDB_Insert_Async(HttpContext _context, EntUser CurrentUser, DateTime requestBeginTime, DateTime requestEndTime
            , string logOperation, string clientIp, string errorMessage)
        {
            await Task.Run(() =>
            {
                LogDB_Insert(_context, CurrentUser, requestBeginTime, requestEndTime, logOperation, clientIp, errorMessage);
            });
        }

        public static void LogDB_Insert(HttpContext _context, EntUser CurrentUser, DateTime requestBeginTime, DateTime requestEndTime
            , string logOperation, string clientIp, string errorMessage)
        {
            try
            {
                EntLog entLog = new EntLog
                {
                    UserId = CurrentUser.UserId,
                    LogOperation = logOperation,
                    RequestAddress = _context.Request.Url.ToString(),
                    RequestParams = GetRequestParams(_context),
                    RequestBeginTime = requestBeginTime,
                    RequestEndTime = requestEndTime,
                    ErrorMessage = errorMessage,
                    ClientIP = clientIp,
                    IpAddress = IPHelper.GetBaiduIpAddress(clientIp),
                };
                if (string.IsNullOrWhiteSpace(errorMessage))
                    entLog.IsError = false;
                else
                    entLog.IsError = true;

                new LSL.SqlClient.BaseDAL().InsertByEntity(entLog);
            }
            catch (Exception ex)
            {
                LogFunction.WriteLog("LogDBHelper-LogDB_Insert", ex);
            }
        }

        public static string GetRequestParams(HttpContext _context)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string key in _context.Request.Form.Keys)
            {
                sb.Append("; " + key + ": " + _context.Request.Form[key]);
            }
            foreach (string key in _context.Request.QueryString.Keys)
            {
                sb.Append("; " + key + ": " + _context.Request.QueryString[key]);
            }
            return sb.ToString().Remove(0, 2);
        }

    }
}
